package com.hellobike.haxing.util;

import com.hellobike.haxing.common.RedisKeyConstant;
import com.hellobike.haxing.user.api.ShopApi;
import com.hellobike.haxing.user.vo.SmallShopVo;
import com.hellobike.haxing.user.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class UserUtil {
    @Autowired
    private RedisUtil redisUtil;

    @Reference(version = "1.0.0")
    private ShopApi shopApi;

    public static ThreadLocal<String> tokenThread = new ThreadLocal<>();


    public UserVo getUser() {
        String token = tokenThread.get();
        if (StringUtils.isBlank(token)) {
            log.error("==获取token为空={}=", token);
            return null;
        } else {
            return getUser(token);
        }
    }

    public UserVo getUser(String token) {
        String idKey = RedisKeyConstant.USER_PREFIX + ":id:" + token;
        Long userId = redisUtil.getVal(Long.class, RedisKeyConstant.USER_PREFIX + ":id:" + token);
        String userKey = RedisKeyConstant.USER_PREFIX + userId;
        Long ttl = redisUtil.ttl(idKey);
        /**
         * 对活跃用户的缓存过期时间增加到7天
         */
        if (ttl < 24 * 60 * 60) {
            redisUtil.expire(userKey, 7L, TimeUnit.DAYS);
            redisUtil.expire(idKey, 7L, TimeUnit.DAYS);
        }
        if (userId != null) {
            UserVo userVo = redisUtil.getObject(UserVo.class, RedisKeyConstant.USER_PREFIX + userId);
            if (userVo != null && userVo.getShopVo() == null) {
                SmallShopVo smallShopVo = shopApi.queryShopByUserId(userVo.getId());
                userVo.setShopVo(smallShopVo);
                redisUtil.setObject(RedisKeyConstant.USER_PREFIX + userId, userVo, 14, TimeUnit.DAYS);
            }
            if (Integer.valueOf(2).equals(userVo.getShopVo().getShopType())) {
                userVo.setUserType(3);
            } else if (Integer.valueOf(3).equals(userVo.getShopVo().getShopType())) {
                userVo.setUserType(4);
            } else {
                userVo.setUserType(2);
            }
            return userVo;
        } else {
            log.error("==获取redis中userID为空==token值={}=", token);
            return null;
        }
    }
}
